package com.yaozheng.vocationaltraining;

import java.io.File;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.xml.JSONTypes;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Fullscreen;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.ImageView;

//import com.nostra13.universalimageloader.core.DisplayImageOptions;
//import com.nostra13.universalimageloader.core.ImageLoader;
//import com.nostra13.universalimageloader.core.assist.FailReason;
//import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.yaozheng.vocationaltraining.activity.BaseActivity;
import com.yaozheng.vocationaltraining.db.JSONDBCacheDao;
import com.yaozheng.vocationaltraining.iview.IBaseView;
import com.yaozheng.vocationaltraining.iview.ITokenBaseView;
import com.yaozheng.vocationaltraining.service.StartupService;
import com.yaozheng.vocationaltraining.service.impl.StartupServiceImpl;
import com.yaozheng.vocationaltraining.utils.BitmapLoader;
import com.yaozheng.vocationaltraining.utils.Constants;
import com.yaozheng.vocationaltraining.utils.ErrorUtils;
import com.yaozheng.vocationaltraining.utils.ImageUtils;
import com.yaozheng.vocationaltraining.utils.JsonUtils;
import com.yaozheng.vocationaltraining.utils.TypeUtils;

import cn.jpush.android.api.JPushInterface;

/**
 * 引导员
 *
 * @author Administrator activity_main
 */
@Fullscreen
@EActivity(R.layout.activity_main)
public class MainActivity extends BaseActivity implements ITokenBaseView {
    @Bean(StartupServiceImpl.class)
    StartupService startupService;

    JSONArray imagesJsonArray;

    String imageUrl;
    @ViewById
    ImageView mainImageView;

    JSONDBCacheDao jsondbCacheDao;

    File localImageFile;

    BitmapLoader bitmapLoader;

    // private DisplayImageOptions displayImageOptions;

    @AfterViews
    public void initView() {
        try {
            JPushInterface.init(getApplicationContext());            // 初始化 JPush
            JPushInterface.resumePush(getApplicationContext());
        } catch (Exception ex) {
            ErrorUtils.outErrorLog(ex);
        }
        startupService.init(this);
        jsondbCacheDao = new JSONDBCacheDao(this);
        localImageFile = new File(getResourcesCachePath()
                + getString(R.string.cacheRootDriStr), "main_image");
        // .bitmapConfig(Bitmap.Config.RGB_565).build();
        bitmapLoader = new BitmapLoader(Glide.with(this), android.R.color.black);
        loadLocalImage();

        loadData();
    }

    public void loadData() {
        try {
            JSONObject jsonObjectData = jsondbCacheDao
                    .getJSONDBCache("main_image_cache");
            if (jsonObjectData != null) {
                String content = TypeUtils.getJsonString(jsonObjectData,
                        JSONDBCacheDao.CONTENT);
                if (content != null && !"".equals(content)) {
                    imagesJsonArray = JsonUtils.getJsonArray(content);
                    updateData();
                }
            }
        } catch (Exception e) {
            ErrorUtils.outErrorLog(e);
        }
        startupService.getStartupData();
    }

    @Override
    public void onReceive(Context context, Intent intent) {
    }

    @UiThread
    public void enterHome() {
        Intent intent = new Intent();
        if (isLogin()) {
            intent.setClassName(this, Constants.HOME_ACTIVITY_CLASS_NAME);
        } else {
            intent.setClassName(this, Constants.LOGIN_CLASS_NAME);
        }
        startActivity(intent);
        finish();

    }

    @Background
    public void remain() {
        try {
            Thread.sleep(1000);
            enterHome();

        } catch (Exception e) {
            ErrorUtils.outErrorLog(e);
        }

    }

    @UiThread
    @Override
    public void responseSuccess(JSONObject jsonObject) {
        JSONArray imagesJsonArray = TypeUtils.getJsonArray(
                TypeUtils.getJsonObject(jsonObject, "data"), "images");
        if (imagesJsonArray != null) {
            try {

                if (this.imagesJsonArray == null
                        || !imagesJsonArray.equals(this.imagesJsonArray)) {
                    this.imagesJsonArray = imagesJsonArray;
                    JSONObject jsonObjectData = new JSONObject();
                    jsonObjectData.put(JSONDBCacheDao.MODULES_NAME,
                            "main_image_cache");
                    jsonObjectData.put(JSONDBCacheDao.CONTENT,
                            imagesJsonArray.toString());
                    jsonObjectData.put(JSONDBCacheDao.ADDITIONAL_CONTENT, "");
                    jsonObjectData.put(JSONDBCacheDao.STATUS, "0");

                    jsondbCacheDao.saveJSONDBCache(jsonObjectData);
                }

                updateData();
                remain();
            } catch (Exception e) {
                ErrorUtils.outErrorLog(e);
            }
        }
    }

    @UiThread
    @Override
    public void responseError(String error) {
        alertMessage(error);
        remain();
    }

    /**
     * 更新数据
     */
    public void updateData() {
        if (imagesJsonArray != null) {
            if (TypeUtils.getJsonArraySize(imagesJsonArray) == 1) {
                updateImage(null);
            } else if (TypeUtils.getJsonArraySize(imagesJsonArray) > 1) {
                JSONObject currJsonObject = null;
                long currTime = System.currentTimeMillis() / 1000;
                for (int i = 0; i < TypeUtils.getJsonArraySize(imagesJsonArray); i++) {
                    currJsonObject = TypeUtils
                            .getJsonObject(imagesJsonArray, i);
                    long startTime = TypeUtils.getJsonLong(currJsonObject,
                            "startTime");
                    long endTime = TypeUtils.getJsonLong(currJsonObject,
                            "endTime");
                    if (currTime >= startTime && currTime < endTime) {
                        break;
                    } else {
                        currJsonObject = null;
                    }
                }
                updateImage(currJsonObject);

            }
        }
    }

    /**
     * 更新图片
     *
     * @param currJsonObject
     */
    private void updateImage(JSONObject currJsonObject) {
        if (imagesJsonArray != null) {
            if (TypeUtils.getJsonArraySize(imagesJsonArray) >= 1) {
                if (currJsonObject == null) {
                    currJsonObject = TypeUtils
                            .getJsonObject(imagesJsonArray, 0);
                }
                String imageUrl = TypeUtils
                        .getJsonString(currJsonObject, "url");
                if (imageUrl == null || imageUrl.equals(this.imageUrl)) {
                    return;
                } else {
                    this.imageUrl = imageUrl;
                    SharedPreferences sharedPreferences = getSharedPreferences();
                    String lastImageUrl = sharedPreferences.getString(
                            "lastImageUrl", "");
                    if (lastImageUrl == null || !lastImageUrl.equals(imageUrl)) {
                        updateImage();
                    }
                }
            }
        }
    }

    /**
     * 更新图片
     */
    private void updateImage() {
        if (imageUrl != null) {
            // ImageLoader.getInstance().loadImage(imageUrl, this);

            Glide.with(this).load(imageUrl).asBitmap()
                    .into(new SimpleTarget<Bitmap>() {

                        @Override
                        public void onResourceReady(Bitmap bitmap,
                                                    GlideAnimation<? super Bitmap> glideAnimation) {
                            try {
                                if (ImageUtils.saveBitmap(bitmap,
                                        localImageFile)) {
                                    SharedPreferences sharedPreferences = getSharedPreferences();
                                    Editor editor = sharedPreferences.edit();
                                    editor.putString("lastImageUrl", imageUrl);
                                    editor.commit();
                                    loadLocalImage();
                                }

                            } catch (Exception e) {
                                ErrorUtils.outErrorLog(e);
                            }
                        }

                    });

        }

    }

    //
    // @Override
    // public void onLoadingCancelled(String arg0, View arg1) {
    //
    // }
    //
    // @Override
    // public void onLoadingComplete(String arg0, View arg1, Bitmap bitmap) {
    // try {
    // if (ImageUtils.saveBitmap(bitmap, localImageFile)) {
    // SharedPreferences sharedPreferences = getSharedPreferences();
    // Editor editor = sharedPreferences.edit();
    // editor.putString("lastImageUrl", arg0);
    // editor.commit();
    // loadLocalImage();
    // }
    //
    // } catch (Exception e) {
    // ErrorUtils.outErrorLog(e);
    // }
    // }

    // @UiThread
    // @Override
    // public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
    // // TODO Auto-generated method stub
    //
    // }
    //
    // @Override
    // public void onLoadingStarted(String arg0, View arg1) {
    // // TODO Auto-generated method stub
    //
    // }

    /**
     * 加载本地图片
     */
    @UiThread
    public void loadLocalImage() {
        if (isResponseResult()) {
            if (localImageFile != null && localImageFile.exists()) {
                try {
                    mainImageView.setImageBitmap(BitmapFactory
                            .decodeFile(localImageFile.getAbsolutePath()));
                } catch (OutOfMemoryError e) {
                    bitmapLoader.displayImage(
                            "file://" + localImageFile.getAbsolutePath(),
                            mainImageView);
                    // ImageLoader.getInstance().displayImage(
                    // "file://" + localImageFile.getAbsolutePath(),
                    // mainImageView, displayImageOptions);
                }
            }
        }
    }
}
